﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using UFC.Common;
using System.Xml;

namespace MESGateWay.WinSMESContainer
{
    public class SendToErpWorkflowInfo
    {
        private const string m_cRecordType = "SendToErpWorkflowInfo";

        /// <summary>
        /// 执行工艺变更数据推送
        /// </summary>
        public void RunContainerSync()
        {
            try
            {
                DataTable dtMains = GetMainContainerWorkflow();//主卡数据
                if (dtMains == null || dtMains.Rows.Count == 0)
                {
                    return;
                }
                string strMsg = "";
                ContainerToERP.PS_SAPServicesHttpService sap = new ContainerToERP.PS_SAPServicesHttpService();
                //分组推送，一次只推送一个待推送的工艺数据
                //DataTable dt = dtMains.DefaultView.ToTable(true, "sendtoerpworkflowinfoid");
                foreach (DataRow dr in dtMains.Rows) //dt.Rows
                {
                    //DataTable dtMain = dtMains.Select(string.Format("sendtoerpworkflowinfoid='{0}'", dr["sendtoerpworkflowinfoid"].ToString())).CopyToDataTable();
                    string ids = "'" + dr["sendtoerpworkflowinfoids"].ToString().Replace(",", "','") + "'";
                    DataTable dtcontainer = GetSendContainerInfo(ids);
                    if (dtcontainer.Rows.Count == 0) //如果没有值，则表示没有需要推送的批次
                    {
                        //更新推送状态为已推送
                        strMsg = "查询不到批次数据";
                        UpdateSendToWorkflowStatus(ids);
                        LogHelp.WriteLog(strMsg);
                        InserOtherSystemRecord(dr["sendtoerpworkflowinfoids"].ToString(), strMsg, strMsg, "1");
                        continue;
                    }
                    DataTable dtworkflow = GetMainWorkflowInfo(dtcontainer.Rows[0]["workflowid"].ToString());
                    DataTable dtComMain = GetAllWorkflowInfo(dtworkflow, dtcontainer.Rows[0]["containerid"].ToString(), ref strMsg);//获取最终的批次工艺路线
                    if (dtComMain.Rows.Count == 0) //如果没有值，则表示存在子工艺工序没有找到对应的子工艺信息
                    {
                        //更新推送状态为已推送
                        strMsg = "查询不到工艺，原因：" + strMsg;
                        UpdateSendToWorkflowStatus(ids);
                        LogHelp.WriteLog(strMsg);
                        InserOtherSystemRecord(dr["sendtoerpworkflowinfoids"].ToString(), strMsg, strMsg, "1");
                        continue;
                    }
                    string strXML = CreateXMLForWorkflowInfo(dtComMain, dr["mfgordername"].ToString());
                    LogHelp.WriteLog("推送的XML：" + strXML);
                    ContainerToERP.ErpAndAppSyncData mm = new ContainerToERP.ErpAndAppSyncData();
                    mm.ReqMsg = strXML;
                    ContainerToERP.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
                    if (result != null)
                    {
                        strMsg = result.RespMsg;
                        LogHelp.WriteLog("返回的消息：" + strMsg);
                        if (GetERPRcvXML(strMsg))
                        {
                            InserOtherSystemRecord(dr["sendtoerpworkflowinfoids"].ToString(), strXML, strMsg, "0");
                        }
                        else
                        {
                            InserOtherSystemRecord(dr["sendtoerpworkflowinfoids"].ToString(), strXML, strMsg, "1");
                        }
                        //更新推送状态为已推送
                        UpdateSendToWorkflowStatus(ids);
                    }
                }
            }
            catch (Exception myError)
            {
                LogHelp.WriteError("推送ERP工艺信息：", myError);
            }
        }

        /// <summary>
        /// 执行热表工艺数据推送（推送商品工时）
        /// </summary>
        public void RunRbCommodityTimeSync()
        {
            try
            {
                DataTable dtMains = GetRBWorkflowData();//待推送的数据
                if (dtMains == null || dtMains.Rows.Count == 0)
                {
                    return;
                }
                string strMsg = "";
                ContainerToERP.PS_SAPServicesHttpService sap = new ContainerToERP.PS_SAPServicesHttpService();
                foreach (DataRow dr in dtMains.Rows) //dt.Rows
                {
                    DataTable dtWorkflow = GetRBWorkflowInfo(dr["workflowid"].ToString());
                    if (dtWorkflow.Rows.Count == 0) //如果没有值，则表示未找到工艺数据
                    {
                        //更新推送状态为已推送
                        strMsg = "查询不到工艺";
                        UpdateSendToWorkflowStatusBySingle(dr["sendtoerpworkflowinfoid"].ToString());
                        LogHelp.WriteLog(strMsg);
                        InserOtherSystemRecord(dr["sendtoerpworkflowinfoid"].ToString(), strMsg, strMsg, "1");
                        continue;
                    }
                    if (dtWorkflow.AsEnumerable().Where(p => !string.IsNullOrWhiteSpace(p["commoditytime"].ToString())).Count() == 0)
                    {
                        //更新推送状态为已推送
                        strMsg = "工艺数据未维护商品工时";
                        UpdateSendToWorkflowStatusBySingle(dr["sendtoerpworkflowinfoid"].ToString());
                        LogHelp.WriteLog(strMsg);
                        InserOtherSystemRecord(dr["sendtoerpworkflowinfoid"].ToString(), strMsg, strMsg, "1");
                        continue;
                    }
                    string strXML = CreateXMLForRBWorkflowInfo(dtWorkflow, dr);
                    LogHelp.WriteLog("推送的XML：" + strXML);
                    ContainerToERP.ErpAndAppSyncData mm = new ContainerToERP.ErpAndAppSyncData();
                    mm.ReqMsg = strXML;
                    ContainerToERP.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
                    if (result != null)
                    {
                        strMsg = result.RespMsg;
                        LogHelp.WriteLog("返回的消息：" + strMsg);
                        if (GetERPRcvXMLByRB(strMsg))
                        {
                            InserOtherSystemRecord(dr["sendtoerpworkflowinfoid"].ToString(), strXML, strMsg, "0");
                        }
                        else
                        {
                            InserOtherSystemRecord(dr["sendtoerpworkflowinfoid"].ToString(), strXML, strMsg, "1");
                        }
                    }
                    //更新推送状态为已推送
                    UpdateSendToWorkflowStatusBySingle(dr["sendtoerpworkflowinfoid"].ToString());
                }
            }
            catch (Exception myError)
            {
                LogHelp.WriteError("推送ERP工艺信息：", myError);
            }
        }

        /// <summary>
        /// 执行热表工艺变更数据推送
        /// </summary>
        public void RunRBWorkflowSync()
        {
            try
            {
                DataTable dtMains = GetMainContainerWorkflowByRB();//主卡数据
                if (dtMains == null || dtMains.Rows.Count == 0)
                {
                    return;
                }
                string strMsg = "";
                ContainerToERP.PS_SAPServicesHttpService sap = new ContainerToERP.PS_SAPServicesHttpService();
                foreach (DataRow dr in dtMains.Rows) //dt.Rows
                {
                    string ids = "'" + dr["sendtoerpworkflowinfoids"].ToString().Replace(",", "','") + "'";
                    DataTable dtcontainer = GetSendContainerInfo(ids);
                    if (dtcontainer.Rows.Count == 0) //如果没有值，则表示没有需要推送的批次
                    {
                        //更新推送状态为已推送
                        strMsg = "（热表）查询不到批次数据";
                        UpdateSendToWorkflowStatus(ids);
                        LogHelp.WriteLog(strMsg);
                        InserOtherSystemRecord(dr["sendtoerpworkflowinfoids"].ToString(), strMsg, strMsg, "1");
                        continue;
                    }
                    DataTable dtworkflow = GetMainWorkflowInfo(dtcontainer.Rows[0]["workflowid"].ToString());
                    if (dtworkflow.Rows.Count == 0) //如果没有值，则表示存在子工艺工序没有找到对应的子工艺信息
                    {
                        //更新推送状态为已推送
                        strMsg = "（热表）查询不到工艺，原因：" + strMsg;
                        UpdateSendToWorkflowStatus(ids);
                        LogHelp.WriteLog(strMsg);
                        InserOtherSystemRecord(dr["sendtoerpworkflowinfoids"].ToString(), strMsg, strMsg, "1");
                        continue;
                    }
                    string strXML = CreateXMLForWorkflowInfo(dtworkflow, dr["mfgordername"].ToString());
                    LogHelp.WriteLog("推送的XML：" + strXML);
                    ContainerToERP.ErpAndAppSyncData mm = new ContainerToERP.ErpAndAppSyncData();
                    mm.ReqMsg = strXML;
                    ContainerToERP.ErpAndAppSyncDataResponse result = sap.ErpAndAppSyncData(mm);
                    if (result != null)
                    {
                        strMsg = result.RespMsg;
                        LogHelp.WriteLog("返回的消息：" + strMsg);
                        if (GetERPRcvXML(strMsg))
                        {
                            InserOtherSystemRecord(dr["sendtoerpworkflowinfoids"].ToString(), strXML, strMsg, "0");
                        }
                        else
                        {
                            InserOtherSystemRecord(dr["sendtoerpworkflowinfoids"].ToString(), strXML, strMsg, "1");
                        }
                        //更新推送状态为已推送
                        UpdateSendToWorkflowStatus(ids);
                    }
                }
            }
            catch (Exception myError)
            {
                LogHelp.WriteError("推送ERP工艺信息：", myError);
            }
        }

        #region 工艺变更方法

        /// <summary>
        /// 获取待推送主卡的数据
        /// </summary>
        /// <returns></returns>
        private DataTable GetMainContainerWorkflow()
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.AppendLine(@"SELECT * FROM (
                        SELECT wm_concat(distinct st.sendtoerpworkflowinfoid) sendtoerpworkflowinfoids,cci.mfgordername
                        FROM SendToErpWorkflowInfo st
                        left join container c on c.containerid = st.containerid
                        LEFT JOIN containersubcontainer csc ON csc.subcontainerid = st.containerid
                        LEFT JOIN containercurrentinfo cci ON cci.containerid = DECODE(csc.containersubcontainerid,NULL,st.containerid,csc.containerid) --如果是子卡，则对应主卡
                        WHERE nvl(st.issenderp,0) = 0 AND cci.mfgordername IS NOT NULL
                        and c.originalfactoryid not in ('0004e2800000281c','0004e280000029f9','0004e280000026e5','0004e280000039ab','0004e280000034c8')--不包含热表、工装、装配、试车、修理
                        GROUP BY cci.mfgordername
                        ) WHERE ROWNUM = 1");
                DataSet myDS = OracleHelper.Query(strSql.ToString());
                if (myDS == null)
                    return null;
                if (myDS.Tables.Count == 0)
                    return null;
                return myDS.Tables[0];
            }
            catch (Exception e)
            {
                LogHelp.WriteError("推送ERP工艺信息查询主卡信息", e);
                return null;
            }
        }

        /// <summary>
        /// 获取待推送主卡数据（热表）
        /// </summary>
        /// <returns></returns>
        private DataTable GetMainContainerWorkflowByRB()
        {
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.AppendLine(@"SELECT wm_concat(distinct sw.sendtoerpworkflowinfoid) sendtoerpworkflowinfoids,cci.mfgordername
                FROM SendToErpWorkflowInfo sw
                INNER JOIN containercurrentinfo cci ON cci.containerid = sw.containerid
                INNER JOIN Userattribute u ON u.parentid = cci.containerid AND u.userattributename = '委托单位'
                WHERE NVL(sw.issenderp,0) = 0 AND sw.operatype IS NULL AND cci.originalfactoryid = '0004e2800000281c' AND sw.createdate >= SYSDATE - 7
                GROUP BY cci.mfgordername");
                DataSet myDS = OracleHelper.Query(strSql.ToString());
                if (myDS == null)
                    return null;
                if (myDS.Tables.Count == 0)
                    return null;
                return myDS.Tables[0];
            }
            catch (Exception e)
            {
                LogHelp.WriteError("（热表）推送ERP工艺信息查询主卡信息", e);
                return null;
            }
        }

        /// <summary>
        /// 获取最新的待推送的主卡
        /// </summary>
        /// <param name="sendToErpWorkflowInfoIds"></param>
        /// <returns></returns>
        private DataTable GetSendContainerInfo(string sendToErpWorkflowInfoIds)
        {
            string sql = string.Format(@"SELECT * FROM (
SELECT DECODE(cci.isinstore,-1,c.mfgworkflowid,0,cci.workflowid,1,cci.bsworkflowid) workflowid,cci.containerid
FROM SendToErpWorkflowInfo st
LEFT JOIN containersubcontainer csc ON csc.subcontainerid = st.containerid
LEFT JOIN container c ON c.containerid = DECODE(csc.containersubcontainerid,NULL,st.containerid,csc.containerid) --如果是子卡，则对应主卡
LEFT JOIN containercurrentinfo cci ON cci.containerid = c.containerid
WHERE st.sendtoerpworkflowinfoid IN ({0})
ORDER BY st.createdate DESC
) k 
WHERE ROWNUM = 1", sendToErpWorkflowInfoIds);
            return OracleHelper.QueryTable(sql, null);
        }

        /// <summary>
        /// 获取主卡工艺信息
        /// </summary>
        /// <param name="workflowid"></param>
        /// <returns></returns>
        private DataTable GetMainWorkflowInfo(string workflowid)
        {
            string sql = string.Format(@"SELECT s.specno,s.opdesc,ws.wipmsglabel,ws.sequence,s.factoryid,ws.workflowstepname,ws.workcentercode,
                        nvl(ws.controlcode,s.controlcode) controlcode,ws.workflowstepid,'' sonspecno,'' sonopdesc
                        FROM workflowstep ws 
                        LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                        LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                        WHERE ws.workflowid  = '{0}'
                        ORDER BY ws.sequence", workflowid);
            return OracleHelper.QueryTable(sql, null);
        }

        /// <summary>
        /// 获取最终的主卡工艺信息
        /// </summary>
        /// <param name="dtMain"></param>
        /// <param name="containerID"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private DataTable GetAllWorkflowInfo(DataTable dtMain, string containerID, ref string msg)
        {
            DataTable dtNew = dtMain.Clone();
            for (int i = 0; i < dtMain.Rows.Count; i++)
            {
                DataRow dr = dtMain.Rows[i];
                dtNew.Rows.Add(dr.ItemArray);
                if (dr["wipmsglabel"].ToString() == "子工艺") //如果该工序是子工艺
                {
                    //先获取子卡工艺信息
                    DataTable dtSonContainer = GetSonContainerWorkflow(containerID, dr["workflowstepid"].ToString());
                    if (dtSonContainer.Rows.Count == 0)
                    {
                        //没有子卡，则取工序自身的子工艺信息
                        dtSonContainer = GetSonStepWorkflow(dr["factoryid"].ToString(), dr["workflowstepid"].ToString());
                        //if (dtSonContainer.Rows.Count == 0) //如果都为空，则报错，不推送（20240110注释掉，原因：没有子工艺也可以推送）
                        //{
                        //    msg = string.Format("推送erp工艺信息失败：工序：{0} 未找到对应的子工艺", dr["workflowstepname"].ToString());
                        //    dtNew.Rows.Clear();
                        //    break;
                        //}
                    }
                    foreach (DataRow item in dtSonContainer.Rows)
                    {
                        dr["sonspecno"] = item["specno"].ToString();
                        dr["opdesc"] = item["opdesc"].ToString();//将工序名称替换为子工序名称
                        dr["sonopdesc"] = item["opdesc"].ToString();
                        dr["workcentercode"] = item["workcentercode"].ToString();//工作中心替换为子工序的
                        dr["controlcode"] = item["controlcode"].ToString();//控制码替换为子工序的
                        dtNew.Rows.Add(dr.ItemArray);
                    }
                }
                //else
                //{
                //    dtNew.Rows.Add(dr.ItemArray);
                //}
            }
            return dtNew;
        }
        /// <summary>
        /// 获取子批次的工艺信息
        /// </summary>
        /// <param name="containerID"></param>
        /// <param name="workflowstepName"></param>
        /// <returns></returns>
        private DataTable GetSonContainerWorkflow(string containerID, string workflowstepID)
        {
            string sql = string.Format(@"SELECT s.specno,s.opdesc,ws.workcentercode,NVL(ws.controlcode,s.controlcode) controlcode
FROM container c
LEFT JOIN containercurrentinfo cci ON cci.containerid = c.containerid
LEFT JOIN workflowstep ws ON ws.workflowid = DECODE(cci.isinstore,-1,c.mfgworkflowid,0,cci.workflowid,1,cci.bsworkflowid)
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
WHERE c.containerid = 
(SELECT max(csc.subcontainerid) FROM containersubcontainer csc
WHERE csc.workflowstepID = '{0}' AND csc.containerid = '{1}' )
ORDER BY ws.sequence", workflowstepID, containerID);
            return OracleHelper.QueryTable(sql, null);
        }

        /// <summary>
        /// 获取工序的子工艺信息
        /// </summary>
        /// <param name="factoryID"></param>
        /// <param name="workflowstepID"></param>
        /// <returns></returns>
        private DataTable GetSonStepWorkflow(string factoryID, string workflowstepID)
        {
            string sql = string.Format(@"select t.* from(
SELECT sbs.workflowid,sbs.workflowstepid,subw.productid subproductid,sbs.sonworkflowid subworkflowid,swb.workflowname subworkflowname,subw.workflowrevision subworkflowrevision FROM stepsubstep sbs
inner join workflow subw on subw.workflowid=sbs.sonworkflowid
left join workflowbase swb on swb.workflowbaseid=subw.workflowbaseid         
left join workflowstep sws on sws.workflowstepid=sbs.sonworkflowstepid--子工艺的工序  
left join specbase sb on sb.specbaseid=sws.specbaseid
left join spec s on s.specid=nvl(sb.revofrcdid,sws.specid)----子工艺的工序
where NVL2(s.commonsubworkflow,'1','0')='0'  
union all
--三层通用子工艺情况下，subproductid非通用工艺的件号，而是第二层虚拟子工艺的件号，这样创出的子卡到时批次调度无法换通用工艺的版本
SELECT sbs.workflowid,sbs.workflowstepid,w.productid subproductid,subw.workflowid subworkflowid,swb.workflowname subworkflowname,subw.workflowrevision subworkflowrevision FROM
(SELECT w.workflowid,w.productid  FROM workflow w
LEFT JOIN workflowstep ws ON ws.workflowid=w.workflowid
WHERE w.factoryid='{0}'
GROUP BY w.workflowid,w.productid
having count(ws.workflowstepid)=1) w--通用工艺情况下，第二层虚拟子工艺 
LEFT JOIN workflowstep ws ON ws.workflowid=w.workflowid
left join specbase sb on sb.specbaseid=ws.specbaseid
left join spec s on s.specid=nvl(sb.revofrcdid,ws.specid)        
INNER join workflow subw on subw.process_no=s.commonsubworkflow--通用孙子工艺
inner join workflowbase swb on swb.revofrcdid=subw.workflowid
LEFT JOIN stepsubstep sbs ON sbs.sonworkflowid=w.workflowid--第二层虚拟子工艺的关联信息
INNER JOIN workflow fw ON fw.workflowid=sbs.workflowid--第一层工艺，主工艺
WHERE   NVL2(s.commonsubworkflow,'1','0')='1' --AND sbs.workflowstepid='00074e80001aa1ab'
GROUP BY sbs.workflowid,sbs.workflowstepid,subw.workflowid,w.productid,swb.workflowname,subw.workflowrevision
 ) t where 1=1 and t.workflowstepid='{1}'", factoryID, workflowstepID);
            DataTable dt = OracleHelper.QueryTable(sql, null);
            if (dt.Rows.Count == 0)
            {
                return new DataTable();
            }
            sql = string.Format(@" SELECT s.specno,s.opdesc,ws.workcentercode,NVL(ws.controlcode,s.controlcode) controlcode
FROM workflowstep ws 
left join specbase sb on sb.specbaseid=ws.specbaseid
left join spec s on s.specid=nvl(sb.revofrcdid,ws.specid)
WHERE ws.workflowid = '{0}' ORDER BY ws.sequence", dt.Rows[0]["subworkflowid"].ToString());
            return OracleHelper.QueryTable(sql, null);
        }

        #endregion

        #region 热表商品工时工艺推送方法

        /// <summary>
        /// 获取热表商品工时待推送的工艺数据
        /// </summary>
        /// <returns></returns>
        private DataTable GetRBWorkflowData()
        {
            string sql = string.Format(@"SELECT sw.sendtoerpworkflowinfoid,cci.mfgordername,cci.productname,cci.productdescription,sw.workflowid
                         FROM SendToErpWorkflowInfo sw
                         INNER JOIN containercurrentinfo cci ON cci.containerid = sw.containerid
                         INNER JOIN Userattribute u ON u.parentid = cci.containerid AND u.userattributename = '委托单位'
                         WHERE NVL(sw.issenderp,0) = 0 AND sw.operatype = '热表商品工时' AND cci.originalfactoryid = '0004e2800000281c'
                         ORDER BY sw.createdate");
            DataSet myDS = OracleHelper.Query(sql);
            if (myDS == null)
            {
                return null;
            }
            if (myDS.Tables.Count == 0)
            {
                return null;
            }
            return myDS.Tables[0];
        }

        /// <summary>
        /// 获取热表工艺信息
        /// </summary>
        /// <param name="workflowid"></param>
        /// <returns></returns>
        private DataTable GetRBWorkflowInfo(string workflowid)
        {
            string sql = string.Format(@"SELECT s.specno,s.opdesc,ws.commoditytime,ws.sequence,s.factoryid,ws.workflowstepname,ws.workcentercode,
                        nvl(ws.controlcode,s.controlcode) controlcode,ws.workflowstepid,'' sonspecno,'' sonopdesc
                        FROM Workflowstep ws 
                        LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                        LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                        WHERE ws.workflowid  = '{0}'
                        ORDER BY ws.sequence", workflowid);
            return OracleHelper.QueryTable(sql, null);
        }

        #endregion

        #region 通用方法

        /// <summary>
        /// 更新推送表
        /// </summary>
        /// <param name="sendtoerpworkflowinfoID"></param>
        private void UpdateSendToWorkflowStatus(string sendtoerpworkflowinfoIDs)
        {
            string sql = string.Format(@"UPDATE SendToErpWorkflowInfo sf SET sf.issenderp = 1 
            WHERE sf.sendtoerpworkflowinfoid IN ({0})", sendtoerpworkflowinfoIDs);
            OracleHelper.ExecuteSql(sql);
        }

        /// <summary>
        /// 更新推送表
        /// </summary>
        /// <param name="sendtoerpworkflowinfoID"></param>
        private void UpdateSendToWorkflowStatusBySingle(string sendtoerpworkflowinfoID)
        {
            string sql = string.Format(@"UPDATE SendToErpWorkflowInfo sf SET sf.issenderp = 1 
            WHERE sf.sendtoerpworkflowinfoid = '{0}'", sendtoerpworkflowinfoID);
            OracleHelper.ExecuteSql(sql);
        }

        /// <summary>
        /// 工艺变更推送XML
        /// </summary>
        /// <param name="dtMain"></param>
        /// <returns></returns>
        private string CreateXMLForWorkflowInfo(DataTable dtMain, string mfgordername)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
                XmlNode ReqNode = doc.CreateElement("ReqMsg");
                XmlNode headerNode = doc.CreateElement("header");
                XmlNode senderNode = doc.CreateElement("sendSysName");
                senderNode.InnerText = "APP_MES";
                XmlNode rcvNode = doc.CreateElement("rcvSysName");
                rcvNode.InnerText = "APP_ERP";
                XmlNode extNode = doc.CreateElement("extConfig");
                extNode.AppendChild(doc.CreateElement("isReTry"));
                extNode.LastChild.InnerText = "false";
                extNode.AppendChild(doc.CreateElement("FunName"));
                extNode.LastChild.InnerText = "ZRFC_MES_ROUTING_MAINTAIN";//方法名
                headerNode.AppendChild(senderNode);
                headerNode.AppendChild(rcvNode);
                headerNode.AppendChild(extNode);
                ReqNode.AppendChild(headerNode);
                XmlNode documentNode = doc.CreateElement("document");
                StringBuilder strData = new StringBuilder();
                strData.Append("<ITEMS>");
                foreach (DataRow dr in dtMain.Rows)
                {
                    strData.Append("<ITEM>");
                    strData.AppendFormat("<AUFNR>{0}</AUFNR>", mfgordername);//生产订单号
                    strData.AppendFormat("<VORNR>{0}</VORNR>", dr["specno"].ToString().Trim() == "0000" ? "0001" : dr["specno"].ToString());//工序号（如果是0000工序号，erp识别不了，只能改为0001）
                    strData.AppendFormat("<LTXA1>{0}</LTXA1>", dr["opdesc"].ToString());//工序名称
                    strData.AppendFormat("<UVORN>{0}</UVORN>", dr["sonspecno"].ToString().Trim() == "0000" ? "0001" : dr["sonspecno"].ToString());//子工序号（同上）
                    strData.AppendFormat("<ARBPL>{0}</ARBPL>", dr["workcentercode"].ToString());//工作中心
                    strData.AppendFormat("<STEUS>{0}</STEUS>", dr["controlcode"].ToString());//控制码
                    strData.AppendFormat("<SAKTO>{0}</SAKTO>", "");//成本要素
                    strData.AppendFormat("<MATKL>{0}</MATKL>", "");//物料组
                    strData.AppendFormat("<EKGRP>{0}</EKGRP>", "");//采购组
                    strData.Append("</ITEM>");
                }
                strData.Append("</ITEMS>");
                documentNode.AppendChild(doc.CreateCDataSection(strData.ToString()));
                ReqNode.AppendChild(documentNode);
                doc.AppendChild(ReqNode);
                return doc.InnerXml;
            }
            catch (Exception e)
            {
                LogHelp.WriteError("生产批次XML", e);
                return string.Empty;
            }
        }

        // <summary>
        /// 热表商品工时推送XML
        /// </summary>
        /// <param name="dtMain"></param>
        /// <returns></returns>
        private string CreateXMLForRBWorkflowInfo(DataTable dtMain, DataRow drContainer)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
                XmlNode ReqNode = doc.CreateElement("ReqMsg");
                XmlNode headerNode = doc.CreateElement("header");
                XmlNode senderNode = doc.CreateElement("sendSysName");
                senderNode.InnerText = "APP_MES";
                XmlNode rcvNode = doc.CreateElement("rcvSysName");
                rcvNode.InnerText = "APP_ERP";
                XmlNode extNode = doc.CreateElement("extConfig");
                extNode.AppendChild(doc.CreateElement("isReTry"));
                extNode.LastChild.InnerText = "false";
                extNode.AppendChild(doc.CreateElement("FunName"));
                extNode.LastChild.InnerText = "ZRFC_MES_OPERATION_VGW_CHANGE";//方法名
                headerNode.AppendChild(senderNode);
                headerNode.AppendChild(rcvNode);
                headerNode.AppendChild(extNode);
                ReqNode.AppendChild(headerNode);
                XmlNode documentNode = doc.CreateElement("document");
                StringBuilder strData = new StringBuilder();
                strData.Append("<ITEMS>");
                foreach (DataRow dr in dtMain.Rows)
                {
                    strData.Append("<ITEM>");
                    strData.AppendFormat("<AUFNR>{0}</AUFNR>", drContainer["mfgordername"].ToString());//订单号
                    strData.AppendFormat("<VORNR>{0}</VORNR>", dr["specno"].ToString().Trim());//工序号
                    strData.AppendFormat("<UVORN>{0}</UVORN>", "");//子工序号
                    strData.AppendFormat("<VGW01>{0}</VGW01>", dr["commoditytime"].ToString());//1000标准值
                    strData.AppendFormat("<VGE01>{0}</VGE01>", "H");//1000标准值单位
                    strData.AppendFormat("<VGW02>{0}</VGW02>", dr["commoditytime"].ToString());//2000标准值
                    strData.AppendFormat("<VGE02>{0}</VGE02>", "H");//2000标准值单位
                    strData.AppendFormat("<VGW03>{0}</VGW03>", dr["commoditytime"].ToString());//3000标准值
                    strData.AppendFormat("<VGE03>{0}</VGE03>", "H");//3000标准值单位
                    strData.AppendFormat("<VGW04>{0}</VGW04>", dr["commoditytime"].ToString());//4000标准值
                    strData.AppendFormat("<VGE04>{0}</VGE04>", "H");//4000标准值单位
                    strData.AppendFormat("<VGW05>{0}</VGW05>", dr["commoditytime"].ToString());//5000标准值
                    strData.AppendFormat("<VGE05>{0}</VGE05>", "H");//5000标准值单位
                    strData.AppendFormat("<VGW06>{0}</VGW06>", "");//6000标准值
                    strData.AppendFormat("<VGE06>{0}</VGE06>", "");//6000标准值单位
                    strData.Append("</ITEM>");
                }
                strData.Append("</ITEMS>");
                documentNode.AppendChild(doc.CreateCDataSection(strData.ToString()));
                ReqNode.AppendChild(documentNode);
                doc.AppendChild(ReqNode);
                return doc.InnerXml;
            }
            catch (Exception e)
            {
                LogHelp.WriteError("生产批次XML", e);
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取ERP反馈XML
        /// </summary>
        /// <param name="strXML"></param>
        /// <returns></returns>
        private bool GetERPRcvXML(string strXML)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strXML);
            string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
            string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;
            bool res = true;
            if (isSuccess == "true" || meaasge == "S")
            {
                XmlDocument docItem = new XmlDocument();
                docItem.LoadXml(doc.SelectSingleNode("RespMsg/document").InnerText);
                XmlNodeList nodeList = docItem.SelectNodes("RT_TABLE/RTITEM");
                foreach (XmlNode item in nodeList)
                {
                    string rtype = item.SelectSingleNode("RTYPE").InnerText;
                    if (rtype == "E")
                    {
                        res = false;
                        break;
                    }
                }
            }
            else
            {
                LogHelp.WriteLog(meaasge);
                res = false;
            }
            return res;
        }

        /// <summary>
        /// 获取ERP反馈XML（热表商品工时）
        /// </summary>
        /// <param name="strXML"></param>
        /// <returns></returns>
        private bool GetERPRcvXMLByRB(string strXML)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strXML);
            string isSuccess = doc.SelectSingleNode("RespMsg/header/isSuccess").InnerText;
            string meaasge = doc.SelectSingleNode("RespMsg/header/message").InnerText;
            bool res = true;
            if (isSuccess == "true" || meaasge == "S")
            {
                XmlDocument docItem = new XmlDocument();
                docItem.LoadXml(doc.SelectSingleNode("RespMsg/document").InnerText);
                XmlNode tettype = docItem.SelectSingleNode("RETTYP");
                XmlNode type = tettype.SelectSingleNode("RTYPE");
                if (type.InnerText == "E")
                {
                    res = false;
                    XmlNode msgxn = tettype.SelectSingleNode("RTMSG");
                    LogHelp.WriteLog(msgxn.InnerText);
                }
            }
            else
            {
                LogHelp.WriteLog(meaasge);
                res = false;
            }
            return res;
        }

        /// <summary>
        /// 插入日志表
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="sendXml"></param>
        /// <param name="resXml"></param>
        public void InserOtherSystemRecord(string ids, string sendXml, string resXml, string isSuccess)
        {
            string[] strs = ids.Split(',');
            foreach (string id in strs)
            {
                //记录日志表
                Dictionary<string, string> recordPara = new Dictionary<string, string>() { 
                        {"ParentId",id},{"RecordType",m_cRecordType},
                        {"SendXml",sendXml},{"ResXml",resXml},{"IsSuccess",isSuccess},
                        {"ContainerID",""},{"ContainerName",""},{"ProductName",""},{"WorkflowStepName",""}};
                OracleDAL.InserOtherSystemRecord(recordPara);
            }
        }
        #endregion
    }
}
